package com.demo.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.beans.Menu;
import com.demo.beans.Permission;
import com.demo.beans.ReturnData;
import com.demo.beans.User;
import com.demo.controller.BaseAction;
import com.demo.mapper.demo.MenuMapper;
import com.demo.mapper.demo.PermissionMapper;
import com.demo.mapper.demo.UserMapper;
import com.demo.service.UserService;
import com.demo.utils.RedisUtil;
import com.demo.utils.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public ReturnData userRegister(User user, HttpServletRequest request){
        ReturnData returnData = BaseAction.createReturnData();
        Map<String,String> bean = new HashMap<String,String>();
        try {
            String ipAddr = getIpAddr(request);
            if (user.getNickName() == null){
                returnData.put("returnCode","9999");
                returnData.put("returnMsg","注册失败，请输入您的昵称！");
                return returnData;
            }
            if (ObjectUtil.isEmpty(user.getPassword())){
                returnData.put("returnCode","9999");
                returnData.put("returnMsg","注册失败，请输入密码！");
                return returnData;
            }
            String userId = RedisUtil.getId("user",redisTemplate);
            user.setUserId(userId);
            Date date = new Date();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
            String insertTime = dateFormat.format(date);
            user.setCreateTime(insertTime);
            user.setRemark("用户" + user.getNickName() + "于" + insertTime + "注册成功，请管理员尽快审核");
            user.setIp(ipAddr);
            user.setState(0);
            String code = RedisUtil.getId("userCode",redisTemplate);
            String userCode = "A" + code;
            user.setUserCode(userCode);
            Integer insertResult = this.userMapper.saveUserInfo(user);
            if (insertResult >= 1){
                returnData.put("returnCode","0000");
                returnData.put("returnMsg","注册成功，请登录");
                bean.put("userCode", userCode);
                returnData.put("bean",bean);
            }else {

            }
        } catch (Exception e) {
            returnData.put("returnCode","9999");
            returnData.put("returnMsg", "异常:" + e.toString());
            e.printStackTrace();
            return returnData;
        }
        return returnData;
    }

    @Override
    public ReturnData userLogin(Map<String, String> params) throws Exception {
        ReturnData returnData = BaseAction.createReturnData();
        User user = null;
        String condition = params.get("condition");
//        Map<String,Object> beans = new HashMap<>();
        user = userMapper.queryUserById(condition);
        if (ObjectUtil.isEmpty(user)){
            user = userMapper.queryUserByName(condition);
            if (ObjectUtil.isEmpty(user)){
                user = userMapper.queryUserByNickname(condition);
                if (ObjectUtil.isEmpty(user)){
                    user = userMapper.queryUserByPhonenumber(condition);
                    if (ObjectUtil.isEmpty(user)){
                        user = userMapper.queryUserByUsercode(condition);
                        if (ObjectUtil.isEmpty(user)){
                            returnData.put("returnCode","9999");
                            returnData.put("returnMsg","账号有误！！");
                            return returnData;
                        }
                    }
                }
            }
        }
        String password = params.get("password");
        if (user.getPassword().equals(password)){
            UserThreadLocal.set(user);
            returnData.put("bean",user);
            returnData.put("returnCode","0000");
            returnData.put("returnMsg","登录成功");
        }
        String userId = user.getUserId();
        //查询用户菜单权限
        List<Menu> menuList = new ArrayList<>();
        List<Menu> pMenuList = new ArrayList<>();
        Menu menu = null;
//        List<Permission> permissions = permissionMapper.queryMenuPermsByUserId(userId);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        List<Permission> permissions = permissionMapper.selectList(wrapper);
        for (Permission permission : permissions) {
            menu = menuMapper.queryMenuById(permission.getMenuId());
            if (ObjectUtil.isNotEmpty(menu)){
                if (1 == menu.getIsParent()){
                    pMenuList.add(menu);
                }else {
                    menuList.add(menu);
                }
            }
        }
        returnData.put("menuList",menuList);
        returnData.put("pMenuList",pMenuList);
        return returnData;
    }

    @Override
    public ReturnData userList(User user) {
        QueryWrapper wrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(user.getNickName())){
            wrapper.eq("nick_name",user.getNickName());
        }
        if (ObjectUtil.isNotEmpty(user.getUserName())){
            wrapper.eq("user_name",user.getUserName());
        }
        if (ObjectUtil.isNotEmpty(user.getUserCode())){
            wrapper.eq("user_code",user.getUserCode());
        }
        if (ObjectUtil.isNotEmpty(user.getPhoneNumber())){
            wrapper.eq("phone_number",user.getPhoneNumber());
        }
        if (ObjectUtil.isNotEmpty(user.getUserId())){
            wrapper.eq("user_id",user.getUserId());
        }
        wrapper.orderByAsc("user_id");
        ReturnData returnData = BaseAction.createReturnData();
        List list = userMapper.selectList(wrapper);
        Integer count = userMapper.selectCount(wrapper);
        if (list.size() > 0){
            returnData.put("returnCode","0000");
            returnData.put("returnMsg","查询成功");
            returnData.put("bean",list);
            returnData.put("count",count);
        }else {
            returnData.put("returnCode","9999");
            returnData.put("returnMsg","未查询到用户信息");
        }
        return returnData;
    }

    @Override
    public ReturnData updateUserState(User user) {
        ReturnData returnData = BaseAction.createReturnData();
        User updateUser = userMapper.queryUserById(user.getUserId());
        if (ObjectUtil.isEmpty(updateUser)){
            returnData.put("returnCode","9999");
            returnData.put("returnMsg","查无此用户信息！");
            return returnData;
        }
        int i = userMapper.updateUserState(user);
        if (i > 0){
            returnData.put("returnCode","0000");
            if (user.getState() == 0){
                returnData.put("returnMsg","修改用户" + updateUser.getUserCode() + "账号状态成功，该用户将无法登录");
            }else {
                returnData.put("returnMsg","修改用户" + updateUser.getUserCode() + "账号状态成功");
            }
        }else {
            returnData.put("returnCode","9999");
            returnData.put("returnMsg","修改用户" + updateUser.getUserCode() + "账号状态成功失败！");
        }
        return returnData;
    }

    public String getIpAddr(HttpServletRequest request) throws Exception{

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-real-ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
//                    log.warn(e.toString());
                }
            }
        }
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }
}
